package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.utils.TimeListUilts;
import com.bjesc_b2c.app.appraiset.widget.dialog.PureTextDialog;
import com.bjesc_b2c.app.appraiset.widget.dialog.TipDialog;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.BasicDropDownPop;
import com.example.codeutils.utils.FileUtils;
import com.example.codeutils.utils.SDCardUtils;
import com.google.gson.Gson;
import com.rxretrofit_build.util.MapUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import master_bean.CarForBean;
import master_bean.ComprehensiveBean;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

import static com.bjesc_b2c.app.appraiset.R.id.cb_auction;

/**
 * Created by lenovo on 2017/2/25.
 * 综合评估
 */

public class ComprehensiveEvaluationActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener, TipDialog.CallBack {
    @InjectView(R.id.tv_car_level)
    TextView carLevelTv;
    @InjectView(R.id.tv_cost_level)
    TextView costLevelTv;
    @InjectView(R.id.edit_consultant_describe)
    EditText consultantDescribeEdit;
    @InjectView(R.id.edit_car_condition_describe)
    EditText carConditionDescribeEdit;
    @InjectView(R.id.edit_seller_responsibility)
    EditText sellerResponsibilityEdit;
    @InjectView(R.id.edit_buyer_responsibility)
    EditText buyerResponsibilityEdit;
    @InjectView(R.id.edit_other_tip)
    EditText otherTipEdit;
    @InjectView(R.id.edit_master_offer)
    EditText masterOfferEdit;
    @InjectView(R.id.edit_floor_price)
    EditText floorPriceEdit;
    @InjectView(R.id.edit_fair)
    EditText fairEdit;
    @InjectView(R.id.edit_new_car_price)
    EditText newCarEdit;
    @InjectView(R.id.cb_direct_sal)
    CheckBox directSalCb;
    @InjectView(cb_auction)
    CheckBox auctionCb;

    private PureTextDialog carLevelDialog;
    private PureTextDialog costLevelDialog;
    private String carLevel = "";
    private String costLevel = "";
    private String isDirecTsal = "publish";         //auction  修改
    private String isAuction = "";           //publish

    private BasicDropDownPop basicPop;
    private TipDialog tipDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comprehensive_evaluation);
        ButterKnife.inject(this);
        basicPop = new BasicDropDownPop(this, this);
        tipDialog = new TipDialog(this, this);
        initViews();
        getData();
    }

    private void getData() {
        HashMap<String, Object> build = new MapUtil()
                .put("id", CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()))
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).getComprehensive()
                , new BaseSubscriber<TokenBean<ComprehensiveBean>>(this) {
                    @Override
                    public void onSuccess(TokenBean<ComprehensiveBean> o) {
                        if (o.getData() != null) {
                            setView(o.getData());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    private void setView(ComprehensiveBean data) {
        if (!TextUtils.isEmpty(data.getAdvisorDesc())) {
            consultantDescribeEdit.setText(data.getAdvisorDesc());
        }
        if (!TextUtils.isEmpty(data.getConditionDesc())) {
            carConditionDescribeEdit.setText(data.getConditionDesc());
        }
        if (!TextUtils.isEmpty(data.getOwner_price())) {
            masterOfferEdit.setText(data.getOwner_price());
        }
        if (!TextUtils.isEmpty(data.getFair_price())) {
            fairEdit.setText(data.getFair_price());
        }
        if (!TextUtils.isEmpty(data.getLow_price())) {
            floorPriceEdit.setText(data.getLow_price());
        }
        if (!TextUtils.isEmpty(data.getNew_price())) {
            newCarEdit.setText(data.getNew_price());
        }
        if (!TextUtils.isEmpty(data.getSynthGrade())) {
            carLevel = data.getSynthGrade();
            if (carLevel.equals("A")) {
                carLevelTv.setText("A");
            } else if (carLevel.equals("B")) {
                carLevelTv.setText("B");
            } else if (carLevel.equals("C")) {
                carLevelTv.setText("C");
            } else if (carLevel.equals("D")) {
                carLevelTv.setText("D");
            }
        }
        if (!TextUtils.isEmpty(data.getSetupGrade())) {
            costLevel = data.getSetupGrade();
            if (costLevel.equals("1")) {
                costLevelTv.setText("++");
            } else if (costLevel.equals("2")) {
                costLevelTv.setText("+");
            } else if (costLevel.equals("3")) {
                costLevelTv.setText("-");
            } else if (costLevel.equals("4")) {
                costLevelTv.setText("--");
            }
        }
        if (data.getTransFeduty() != null) {
            if (!TextUtils.isEmpty(data.getTransFeduty().getOne())) {
                sellerResponsibilityEdit.setText(data.getTransFeduty().getOne());
            }
            if (!TextUtils.isEmpty(data.getTransFeduty().getTwo())) {
                buyerResponsibilityEdit.setText(data.getTransFeduty().getTwo());
            }
            if (!TextUtils.isEmpty(data.getTransFeduty().getThree())) {
                otherTipEdit.setText(data.getTransFeduty().getThree());
            }
        }
    }


    private void initViews() {
        directSalCb.setOnCheckedChangeListener(this);
        auctionCb.setOnCheckedChangeListener(this);
    }

    @OnClick({R.id.rl_return, R.id.tv_save_info, R.id.rlty_car_level, R.id.rlty_cost_level, R.id.btn_previous_page,
            R.id.btn_next_page, R.id.rlty_title})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_return:            //返回
                finish();
                break;
            case R.id.tv_save_info:         //保存信息
                saveInfo();
                break;
            case R.id.rlty_car_level:       //车况等级
                carLevelDialog = new PureTextDialog(this, carLevelListener, TimeListUilts.getCarLevelList(), "车况等级");
                carLevelDialog.show();
                break;
            case R.id.rlty_cost_level:      //成本等级
                costLevelDialog = new PureTextDialog(this, costLevelListener, TimeListUilts.getCostLevelList(), "成本等级");
                costLevelDialog.show();
                break;
            case R.id.btn_previous_page:    //上一页
                startIntent(new Intent(ComprehensiveEvaluationActivity.this, CarSourceActivity.class), true);
                break;
            case R.id.btn_next_page:        // 提交
//                startIntent(new Intent(ComprehensiveEvaluationActivity.this, PhotographsActivity.class), true);
                tipDialog.show();
                break;
            case R.id.rlty_car_form:        //车源图片
                startIntent(new Intent(ComprehensiveEvaluationActivity.this, CarSourceActivity.class), true);
                break;
            case R.id.rlty_car_Framework:   //骨架
                startIntent(new Intent(ComprehensiveEvaluationActivity.this, CarFrameworkImageActivity.class), true);
                break;
            case R.id.rlty_car_appearance:  //外观
                startIntent(new Intent(ComprehensiveEvaluationActivity.this, CarSurfaceItemActivity.class), true);
                break;
            case R.id.rlty_car_interior:    //内饰
                startIntent(new Intent(ComprehensiveEvaluationActivity.this, CarOrnamentsItemActivity.class), true);
                break;
            case R.id.rlty_car_damage:      //配置
                startIntent(new Intent(ComprehensiveEvaluationActivity.this, DeviceActivity.class), true);
                break;
            case R.id.rlty_car_comprehensive:   //综合评估
                basicPop.dismiss();
                break;
            case R.id.rlty_car_photo:       //合影
                startIntent(new Intent(ComprehensiveEvaluationActivity.this, PhotographsActivity.class), true);
                break;
            case R.id.rlty_title:
                basicPop.showAsDropDown(findViewById(R.id.rlty_title));
                break;
        }
    }

    private void saveInfo() {
        HashMap<String, Object> build = new MapUtil()
                .put("id", CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()))
                .put("data", new Gson().toJson(getSaveBean()))
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).saveComprehensive()
                , new BaseSubscriber<TokenBean>(this) {
                    @Override
                    public void onSuccess(TokenBean o) {

                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    private ComprehensiveBean getSaveBean() {
        ComprehensiveBean.TransFedutyBean bean = new ComprehensiveBean.TransFedutyBean();
        bean.setOne(sellerResponsibilityEdit.getText().toString());
        bean.setTwo(buyerResponsibilityEdit.getText().toString());
        bean.setThree(otherTipEdit.getText().toString());
        ComprehensiveBean comprehensiveBean = new ComprehensiveBean();
        comprehensiveBean.setId(CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()));
        comprehensiveBean.setSynthGrade(carLevel); //综合车况等级
        comprehensiveBean.setSetupGrade(costLevel); //整备成本等级
        comprehensiveBean.setIs_status(getIsStatus());
        comprehensiveBean.setAdvisorDesc(consultantDescribeEdit.getText().toString());
        comprehensiveBean.setConditionDesc(carConditionDescribeEdit.getText().toString());
        comprehensiveBean.setTransFeduty(bean);
        comprehensiveBean.setOwner_price(masterOfferEdit.getText().toString());
        comprehensiveBean.setLow_price(floorPriceEdit.getText().toString());
        comprehensiveBean.setFair_price(fairEdit.getText().toString());
        comprehensiveBean.setNew_price(newCarEdit.getText().toString());
        return comprehensiveBean;
    }

    private List<String> getIsStatus() {
        List<String> isStatus = new ArrayList<>();
        if (!TextUtils.isEmpty(isAuction)) {
            isStatus.add(isAuction);
        }
        if (!TextUtils.isEmpty(isDirecTsal)) {
            isStatus.add(isDirecTsal);
        }
        return isStatus;
    }

    private PureTextDialog.OnSelectListener carLevelListener = new PureTextDialog.OnSelectListener() {
        @Override
        public void onSelect(String text, String index) {
            carLevel = text;
            carLevelTv.setText(text);
        }
    };
    private PureTextDialog.OnSelectListener costLevelListener = new PureTextDialog.OnSelectListener() {
        @Override
        public void onSelect(String text, String index) {
            costLevel = index;
            costLevelTv.setText(text);
        }
    };

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        switch (compoundButton.getId()) {
            case R.id.cb_direct_sal:    //直卖

                if (b) {
                    isDirecTsal = "publish";
                } else {
                    isDirecTsal = "";
                }
                break;
            case cb_auction:      //拍卖
                if (b) {
                    isAuction = "auction";
                } else {
                    isAuction = "";
                }
                break;
        }

    }

    @Override
    public void callBack() {
        putData();
    }

    private void putData() {
        final String carId = CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf());
        HashMap<String, Object> build = new MapUtil()
                .put("id", carId)
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).putCar()
                , new BaseSubscriber<TokenBean<CarForBean>>(this) {
                    @Override
                    public void onSuccess(TokenBean<CarForBean> o) {
                        tipDialog.dismiss();

                        if(o.getStatus_code() == 0) {
                            FileUtils.deleteDir(SDCardUtils.getDataPath() + carId);//上传成功清除文件缓存
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }
}
